package com.simulation.Service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.simulation.Service.ApiRequestLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;

/**
 * @Auther: xh
 * @Date: 2019/8/17 07:39
 * @Description:
 */
public class ApiRequestLogServiceImpl implements ApiRequestLogService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private final String REQEUST_TIME = "REQEUST_TIME";
    private final String REQEUST_URL = "REQEUST_URL";
    private final String REQEUST_PARAM = "REQEUST_PARAM";

    private ObjectMapper objectMapper;

    public ApiRequestLogServiceImpl(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void preLog(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //Log输出：请求路径、请求参数（**application/json** 除外）
        try {
            String url = request.getRequestURL().toString();
            Map<String, String[]> parameterMap = request.getParameterMap();
            String paramStr = objectMapper.writeValueAsString(parameterMap);
            MDC.put(REQEUST_URL, url);
            MDC.put(REQEUST_PARAM, paramStr);
            logger.info(">> url: {}, param: {}", url, paramStr);

            Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            MDC.put(REQEUST_TIME, milliSecond.toString());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postLog(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        //响应时间
        Long time = milliSecond - Long.valueOf(MDC.get(REQEUST_TIME));
        logger.info("<< url: {}, param: {}, resTime:{}", MDC.get(REQEUST_URL),MDC.get(REQEUST_PARAM),time);
    }

    @Override
    public void exceptionLog(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if(ex!=null)
        logger.info("<< url: {}, param: {}, exception:{}", MDC.get(REQEUST_URL),MDC.get(REQEUST_PARAM),ex.toString());
    }
}
